package com.training1.core.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.training1.core.common.dao.Page;
import com.training1.core.common.entity.RespJson;
import com.training1.core.common.global.signIn.LoginInfo;
import com.training1.core.common.utils.framework.RespJsonFactory;
import com.training1.core.entity.NoticeMsgEntity;
import com.training1.core.modules.service.NoticeMsgService;

@Controller
@RequestMapping("noticeMsg")
public class NoticeMsgConntroller {
	
	@Resource
	private NoticeMsgService noticeMsgService;
	
	//时间工具方法
		public static Date formatDate(String str) throws Exception{
			 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			 Date date=formatter.parse(str);
			 return date;
		}
	
	/**
	 * 进入消息列表页面
	 * @return
	 */
	@RequestMapping(value={"/",""})
	public String go(){
		return "noticeMsg/noticeMsg";
	}
	
	/**
	 * 查询及列表往页面传值
	 * @param page
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("list")
	@ResponseBody
	public Page<NoticeMsgEntity> list(String msgTitle,String startTime,String endTime,Page<NoticeMsgEntity> page) throws Exception{
		page.getSearch().put("msgTitle", msgTitle);
		if(startTime!=null&startTime!=""){//判断接受过来的时间是否为空
			page.getSearch().put("startTime", formatDate(startTime));
		}
		if(endTime!=null&endTime!=""){
			page.getSearch().put("endTime", formatDate(endTime));
		}
		noticeMsgService.findList(page.getSearch());
		return page;
	}
	
	/**
	 * 查看单个具体消息
	 * @return
	 */
	@RequestMapping("detail")
	@ResponseBody
	public NoticeMsgEntity detail(String id) {
		return noticeMsgService.findOne(Integer.valueOf(id));
	}
	
	/**
	 * 新增保存
	 * @param help
	 * @param result
	 * @return
	 */
	@RequestMapping(value="save", method={RequestMethod.POST})
	@ResponseBody
	public RespJson save(@Valid NoticeMsgEntity noticeMsg, BindingResult result,HttpServletRequest request){
		if(result.hasErrors()){
			return RespJsonFactory.buildFailure(result.getAllErrors().get(0).getDefaultMessage(), "model.help.save.error");
		}
		
		//获得session中登陆的用户名
		HttpSession session = request.getSession();
		LoginInfo lo=(LoginInfo) session.getAttribute("LOGININFO");
		//设置NoticeMsgEntity中的userName和type
		noticeMsg.setUserName(lo.getLoginName());
		noticeMsg.setType(1);
		noticeMsgService.save(noticeMsg);
		return RespJsonFactory.buildSuccess();
	} 
}
